package LinkedList;

import org.w3c.dom.NodeList;

public class LeetCode142_detectCycle {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public ListNode detectCycle(ListNode head) {
        if (head ==null)return null;
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null || fast.next != null) {
            if (slow == fast) {
                ListNode ptr = head;
                while (ptr != slow){
                    ptr = ptr.next;
                }
                return ptr;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
       return null;



/**
 *     if (head == null || head.next == null) return null;
 *
 *         ListNode slow = head;
 *         ListNode fast = head;
 *
 *         // 检测是否有环
 *         while (fast != null && fast.next != null) {
 *             slow = slow.next;
 *             fast = fast.next.next;
 *
 *             if (slow == fast) {
 *                 // 找到环后，寻找环的入口
 *                 ListNode ptr = head;
 *                 while (ptr != slow) {
 *                     ptr = ptr.next;
 *                     slow = slow.next;
 *                 }
 *                 return ptr;
 *             }
 *         }
 *
 *         return null; // 无环
 *     }
 */
    }
}
